package com.expert.miniapp.controller;

import com.expert.miniapp.dao.Laboratory;
import com.expert.miniapp.dao.LaboratoryMapper;
import com.expert.miniapp.dto.ResultDTO;
import com.expert.miniapp.service.LaboratoryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 实验室控制器
 * 提供实验室相关的REST API接口
 */
@RestController
@RequestMapping("/api/laboratories")
@CrossOrigin(origins = "*")
public class LaboratoryController {

    @Autowired
    private LaboratoryService laboratoryService;

    @Autowired
    private LaboratoryMapper laboratoryMapper;

    /**
     * 根据ID获取实验室详情
     * @param id 实验室ID
     * @return 实验室详情
     */
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<Laboratory> getLaboratoryDetails(@PathVariable String id) {
        try {
            Laboratory laboratory = laboratoryService.getLaboratoryById(id);
            if (laboratory != null) {
                return ResultDTO.success(laboratory);
            } else {
                return ResultDTO.error("实验室不存在");
            }
        } catch (Exception e) {
            return ResultDTO.error("查询实验室失败: " + e.getMessage());
        }
    }

    /**
     * 获取实验室列表（支持分页、分类筛选、权重推荐、模糊搜索）
     * @param pageNum 页码（可选）
     * @param pageSize 每页数量（可选）
     * @param category 分类（可选）
     * @param sortBy 排序方式，weight表示按权重推荐（可选）
     * @param keyword 搜索关键词（可选）
     * @return 实验室列表
     */
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<PageInfo<Laboratory>> getLaboratoryList(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String keyword) {
        try {
            PageInfo<Laboratory> pageInfo;

            if (keyword != null && !keyword.trim().isEmpty()) {
                pageInfo = laboratoryService.searchLaboratories(keyword, pageNum, pageSize);
            } else if ("weight".equalsIgnoreCase(sortBy)) {
                pageInfo = laboratoryService.getRecommendedLaboratories(pageNum, pageSize);
            } else if (category != null && !category.trim().isEmpty()) {
                pageInfo = new PageInfo<>(laboratoryService.getLaboratoriesByCategory(category));
            } else {
                pageInfo = laboratoryService.getAllLaboratories(pageNum, pageSize);
            }

            return ResultDTO.success(pageInfo);
        } catch (Exception e) {
            return ResultDTO.error("查询实验室列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类统计实验室数量
     * @param category 分类名称（如："人工智能"）
     * @return 包含该分类的实验室数量
     */
    @GetMapping(value = "/categories/statistics", produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ResultDTO<Map<String, Integer>> getCountByCategory(@RequestParam String category) {
        try {
            Integer count = laboratoryMapper.countByCategory(category);
            Map<String, Integer> result = new HashMap<>();
            result.put("count", count != null ? count : 0);
            return ResultDTO.success(result);
        } catch (Exception e) {
            return ResultDTO.error("统计实验室数量失败: " + e.getMessage());
        }
    }
}